#!/usr/bin/env python
import os
import sys

base_dir = os.path.abspath(os.path.dirname(os.getcwd()))
sys.path.append(base_dir)

import shutil
from pathlib import Path

from app.models import courseModel, coursewareModel
from app.models.courseModel import Chapter, Course, gen_id
from app.models.coursewareModel import Courseware
from manage import app
from tools import db


def list_dir(path: Path, res):
    for i in path.iterdir():
        if i.is_dir():
            temp = {
                "dirname": i.absolute(),
                "child_dirs": [],
                "files": [],
            }
            res["child_dirs"].append(list_dir(i, temp))
        else:
            res["files"].append(i)
    return res


def get_config_dirs(path):
    res = {"child_dirs": [], "files": []}
    path = Path(path)
    if not path.exists():
        print("路径不存在")
        sys.exc_info()
    return list_dir(path, res)


def upload_file(src_file: Path):
    try:
        from configs.settings import BASE_DIR
        from utils.utils import create_md5

        filename = create_md5(src_file.stem)
        file_path = BASE_DIR / "app/api/v1/organizer/path"
        if file_path.exists():
            os.makedirs(file_path, exist_ok=True)
        shutil.copy(src_file, file_path / filename)
        return filename
    except Exception as e:
        raise e


def read_write(path):
    file_directory_dict = get_config_dirs(path)
    try:
        with app.app_context():
            for course_dict in file_directory_dict["child_dirs"]:
                if not course_dict["child_dirs"]:
                    continue
                with db.auto_commit():
                    # 新建课程，关联章节，关联用户
                    course_uuid = gen_id()
                    course = Course()
                    course.id = (course_uuid,)
                    course.name = course_dict["dirname"].stem
                    course.user_id = 1
                    course.isSystem = 1
                    db.session.add(course)
                    db.session.commit()

                    for chapter_dict in course_dict["child_dirs"]:
                        chapter_uuid = gen_id()
                        chapter = Chapter()
                        chapter.id = chapter_uuid
                        chapter.course_id = course_uuid
                        chapter.name = chapter_dict["dirname"].stem
                        db.session.add(chapter)
                        db.session.commit()

                        # 将指定的课件添加到章节下面, 将指定的章节添加到课程下面
                        for courseware_info in chapter_dict["files"]:
                            video_path = pdf_path = None
                            source_end = courseware_info.suffix
                            if source_end in [".mp4", ".wmv", ".avi", ".swf", ".flv"]:
                                video_path = upload_file(courseware_info)
                                type_ = "2"
                            elif source_end in [
                                ".ppt",
                                ".pptx",
                                ".pdf",
                                ".doc",
                                ".docx",
                                ".xls",
                                ".xlsx",
                            ]:
                                pdf_path = upload_file(courseware_info)
                                type_ = "1"

                            if video_path or pdf_path:
                                courseware_name = courseware_info.stem
                                if not coursewareModel.Courseware.query.filter_by(
                                    name=courseware_name
                                ).first():
                                    courseware = Courseware()
                                    courseware.name = courseware_name
                                    courseware.type = type_
                                    courseware.user_id = 1
                                    courseware.isSystem = 1
                                    courseware.pdfPath = pdf_path
                                    courseware.videoPath = video_path
                                    db.session.add(courseware)
                                    db.session.commit()
                                    print(f"正在导入课件：{courseware_name}")
                                    chapter_obj = courseModel.Chapter.query.get(
                                        chapter_uuid
                                    )
                                    courseware_obj = (
                                        coursewareModel.Courseware.query.filter_by(
                                            name=courseware_name
                                        ).first()
                                    )
                                    if courseware_obj not in chapter_obj.coursewares:
                                        chapter_obj.coursewares.append(courseware_obj)
    except Exception as e:
        db.session.rollback()
        raise e
    print("OK")


if __name__ == "__main__":
    path = input("请输入导入目录:")
    read_write(path)
